package com.yourbatis;

import java.io.File;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class SetUpSystem {
    private Configuration configuration;

    private final Map<String, MapperFile> mapperMap = new HashMap();

    public SetUpSystem setUp(Configuration configuration) {
        this.configuration = configuration;
        // 获取Mapper包名
        // 设置所有的代理类
        URL url = SetUpSystem.class.getClassLoader().getResource(configuration.getMapperPath());
        if (url != null) {
            // 如果是文件系统
            File resourcesDir = new File(url.getPath());
            File[] files = resourcesDir.listFiles();
            // TODO 遍历下级文件夹
            if (files != null) {
                for (File file : files) {
                    System.out.println(file.getAbsolutePath());
                    MapperFile mapperFile = new MapperFile(file.getAbsolutePath());
                    mapperMap.put( mapperFile.getClassPath(), mapperFile);
                }
            }
        }
        return this;
    }

    public <T> T getMapper(Class<T> mapperClass) {
        // 获取Mapper包名
        String name = mapperClass.getName();
        MapperFile mapperFile = mapperMap.get(name);
        // 然后根据包名找到所有的Mapper
        //
        // 创建代理对象
        T proxyInstance = (T) Proxy.newProxyInstance(
                mapperClass.getClassLoader(),
                new Class[]{mapperClass},
                new DynamicProxyHandler(mapperClass, mapperFile)
        );
        return proxyInstance;
    }

    public Map getMapperMap() {
        return mapperMap;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }


}
